from PyQt5.QtWidgets import QApplication, QMainWindow, QListWidget, QVBoxLayout, QWidget, QPushButton, QLabel, QMessageBox, QStatusBar, QTextEdit, QHBoxLayout
from PyQt5.QtGui import QColor
import pywinauto
import pyautogui
import pyperclip
import time
import logging
import sys

# 设置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Application Selector")
        self.resize(800, 600)  # 设置窗口大小为800x600

        # 创建状态栏
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)  # 将状态栏添加到主窗口

        # 创建窗口列表
        self.listWidget = QListWidget(self)
        self.listWidget.setSelectionMode(QListWidget.MultiSelection)

        # 创建多行文本输入框
        self.textInput = QTextEdit(self)
        self.textInput.setPlaceholderText("Enter text to insert")
        self.textInput.setMinimumHeight(100)  # 设置最小高度为100像素

        # 创建按钮
        self.insertButton = QPushButton("Insert Text", self)
        self.insertButton.clicked.connect(self.insert_text_to_selected_apps)
        self.insertButton.setStyleSheet("background-color: lightblue;")  # 设置按钮颜色

        self.refreshButton = QPushButton("Refresh Applications", self)
        self.refreshButton.clicked.connect(self.refresh_applications_list)
        self.refreshButton.setStyleSheet("background-color: lightgreen;")  # 设置按钮颜色

        self.deselectAllButton = QPushButton("Deselect All", self)
        self.deselectAllButton.clicked.connect(self.clear_selection)
        self.deselectAllButton.setStyleSheet("background-color: lightcoral;")  # 设置按钮颜色

        self.clearButton = QPushButton("Clear Text", self)
        self.clearButton.clicked.connect(self.clear_text)
        self.clearButton.setStyleSheet("background-color: yellow;")  # 设置按钮颜色

        self.copyButton = QPushButton("Copy Text", self)
        self.copyButton.clicked.connect(self.copy_text)
        self.copyButton.setStyleSheet("background-color: lightcyan;")  # 设置按钮颜色

        self.pasteButton = QPushButton("Paste Text", self)
        self.pasteButton.clicked.connect(self.paste_text)
        self.pasteButton.setStyleSheet("background-color: lightgoldenrodyellow;")  # 设置按钮颜色

        # 按钮布局（两行，每行三列）
        buttonLayout1 = QHBoxLayout()  # 第一行按钮布局
        buttonLayout1.addWidget(self.insertButton)
        buttonLayout1.addWidget(self.refreshButton)
        buttonLayout1.addWidget(self.deselectAllButton)

        buttonLayout2 = QHBoxLayout()  # 第二行按钮布局
        buttonLayout2.addWidget(self.clearButton)
        buttonLayout2.addWidget(self.copyButton)
        buttonLayout2.addWidget(self.pasteButton)

        # 主布局
        layout = QVBoxLayout()
        layout.addWidget(QLabel("Select Applications:"))
        layout.addWidget(self.listWidget)
        layout.addWidget(QLabel("Text to Insert:"))
        layout.addWidget(self.textInput)
        layout.addLayout(buttonLayout1)  # 添加第一行按钮布局
        layout.addLayout(buttonLayout2)  # 添加第二行按钮布局

        self.centralWidget = QWidget(self)
        self.centralWidget.setLayout(layout)
        self.setCentralWidget(self.centralWidget)

        # 初始化高亮显示
        self.refresh_applications_list()

    def refresh_applications_list(self):
        """刷新并填充窗口列表"""
        logging.info("Refreshing application list...")
        try:
            self.listWidget.clear()
            desktop = pywinauto.Desktop(backend="uia")
            windows = desktop.windows(visible_only=True)
            window_titles = [window.window_text().strip() for window in windows if window.window_text().strip()]
            for title in window_titles:
                self.listWidget.addItem(title)
        except Exception as e:
            logging.error(f"Error refreshing applications: {e}")
            QMessageBox.critical(self, "Error", "Failed to refresh applications. Please check your system permissions.")

    def clear_selection(self):
        """取消所有选择"""
        self.listWidget.clearSelection()

    def insert_text_to_selected_apps(self):
        """在选定的应用程序中插入文本"""
        selected_items = self.listWidget.selectedItems()
        text = self.textInput.toPlainText()  # 获取多行文本内容

        if not selected_items:
            QMessageBox.warning(self, "Warning", "No applications selected.")
            return

        if not text:
            QMessageBox.warning(self, "Warning", "No text entered.")
            return

        self.statusBar.clearMessage()
        total_apps = len(selected_items)
        failed_apps = []
        for idx, item in enumerate(selected_items):
            window_title = item.text()
            try:
                desktop = pywinauto.Desktop(backend="uia")
                window = desktop.window(title=window_title)
                if window.exists():
                    if window.is_visible():
                        window.set_focus()
                        time.sleep(0.5)  # 确保窗口获得焦点
                        pyperclip.copy(text)
                        pyautogui.hotkey('ctrl', 'v')
                        logging.info(f"Successfully inserted text into window using pyautogui: {window_title}")
                    else:
                        logging.warning(f"Window is not visible: {window_title}")
                        failed_apps.append(window_title)
                else:
                    logging.warning(f"Window not found: {window_title}")
                    failed_apps.append(window_title)
            except Exception as e:
                logging.error(f"An unexpected error occurred when inserting text into window {window_title}: {e}")
                failed_apps.append(window_title)

        if failed_apps:
            failed_message = "\n".join(failed_apps)
            QMessageBox.warning(self, "Warning", f"Failed to insert text into the following applications:\n{failed_message}\nRefresh Again")
            # 刷新一下
            self.refresh_applications_list()
        else:
            self.statusBar.showMessage("Text inserted successfully into all selected applications.")

    def clear_text(self):
        """清除文本输入框内容"""
        self.textInput.clear()

    def copy_text(self):
        """复制文本输入框内容到剪贴板"""
        text = self.textInput.toPlainText()
        if text:
            pyperclip.copy(text)
            self.statusBar.showMessage("Text copied to clipboard.")
        else:
            QMessageBox.warning(self, "Warning", "No text to copy.")

    def paste_text(self):
        """从剪贴板粘贴内容到文本输入框"""
        clipboard_text = pyperclip.paste()
        self.textInput.setText(clipboard_text)
        self.statusBar.showMessage("Text pasted from clipboard.")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())